package service

import (
	"log"
	"net/http"
	"strings"

	"github.com/gin-gonic/gin"
	"github.com/lzppppppp/virapaksa-go/internal/monitor_check_agent/handler"
)

func PostKeywordCheckAgent(context *gin.Context) {

	var param handler.CheckDataAgent
	err := context.BindJSON(&param) // 前后端交互参数
	if err != nil {                 // 错误处理
		log.Printf("ERROR: Port check failed, error is %v", err)
		context.JSON(500, gin.H{"err": err})
		return
	}

	portMap := map[string]string{
		"process": "10905",
		"port":    "10914",
		"sys":     "10916",
	}

	var reOutCome string

	for _, ip := range param.IP {

		var keywordsArr []string
		var reOutComeSingle, headWord string

		if param.Type == "port" { // 关键字内容识别标识
			headWord = "port_up"
		} else {
			headWord = "process_active_count"
		}

		targetUrl := "http://" + ip + ":" + portMap[param.Type] + "/metrics"
		data, err := handler.GetData(targetUrl, param.TimeOut)
		if err != nil {
			reOutComeSingle = ip + " " + param.Type + " port check failed"
		} else {
			dataArr := strings.Split(data, "\n")

			for _, vv := range dataArr { // 根据关键字标识识别内容
				if strings.HasPrefix(vv, headWord) {
					singleDataArr := strings.Split(vv, "\"")
					keywordsArr = append(keywordsArr, "\""+singleDataArr[1]+"\"")
				}
			}

			if len(keywordsArr) == 1 { // 只有一个关键字情况
				reOutComeSingle = ip + " [" + keywordsArr[0] + "]"
			} else if len(keywordsArr) == 0 { // 端口起着但是关键字为空的情况
				reOutComeSingle = ip + " [ ]"
			} else { // 有多个关键字情况
				for i, k := range keywordsArr {
					if i == 0 {
						reOutComeSingle = ip + " [" + k + ","
					} else if i == len(keywordsArr)-1 {
						reOutComeSingle = reOutComeSingle + k + "]"
					} else {
						reOutComeSingle = reOutComeSingle + k + ","
					}
				}
			}

		}
		reOutCome = reOutCome + reOutComeSingle + "\n"
	}

	type jsonData struct {
		Code int
		Data string
	}
	data := jsonData{
		Code: 200,
		Data: reOutCome,
	}
	context.JSON(http.StatusOK, data)
}
